package com.dh.convert.rule.function;

import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.type.AviatorNil;
import com.googlecode.aviator.runtime.type.AviatorObject;
import com.googlecode.aviator.runtime.type.AviatorRuntimeJavaType;

public class JSONDFunction extends AbstractFunction {

	@Override
	public AviatorObject call(Map<String, Object> env, AviatorObject arg) {
		return call(env,arg,null);
	}
	
	@Override
	public AviatorObject call(Map<String, Object> env, AviatorObject arg,AviatorObject arg2) {
		String result = null;
		Object value = arg.getValue(env);
		if (value == null)
			return  AviatorNil.NIL;
		if (value instanceof Character) {
			result = value.toString();
		} else {
			result = (String) value;
		}
		if(arg2==null){
			return new AviatorRuntimeJavaType(JSON.parse(result));
		}
		Object className = arg2.getValue(env);
		try {
			return new AviatorRuntimeJavaType(JSON.parseObject(result,Class.forName((String)className)));
		} catch (ClassNotFoundException e) {
		} 
		return AviatorNil.NIL;
	}

	@Override
	public String getName() {
		return "JSOND";
	}

}